<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="httpRequest"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDPecJkunPmrfCSSAbleGbfSyDBuMXR4RN',
  SecretKey: 'h7H9k48vRgfOq0tWsxmMefPs51f29zXo'
})
export default {
  data() {
    return {
      imageUrl: '',
      imgUrl:
        'http://dhf481229-1305249343.cos.ap-guangzhou.myqcloud.com/1636077974563'
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpRequest(data) {
      console.log(data)
      cos.putObject(
        {
          Bucket: 'hrdime-1308138744' /* 必须 */,
          Region: 'ap-hongkong' /* 存储桶所在地域，必须字段 */,
          Key: data.file.uid + '',
          StorageClass: 'STANDARD' /* 必须 */,
          Body: data.file,
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          this.imageUrl = 'http://' + data.Location
        }
      )
    },
    sot() {
      this.$i18n.locale = this.$i18n.locale === 'zh' ? 'en' : 'zh'
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
